<template>
  <div class="container">
    <salaryTopTitle
      @gobackTriser="goBack"
      :salaryOperate="salaryOperate"
      :salaryExcel="salaryExcel"
    ></salaryTopTitle>

    <div class="mainCon">
      <createSalaryStep
        :lastItem="lastItem"
        :activeIndex="activeIndex"
      ></createSalaryStep>
      <div class="spacing"></div>
      <el-row
        class="toolbar searchInputWidth"
        style="margin-top: 30px !important"
      >
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item
              label="所属部门"
              class="row-padding-bottom searchInput"
            >
              <el-cascader
                v-model="orgId"
                :options="orglist"
                :props="{ checkStrictly: true }"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="姓名" class="row-padding-bottom">
              <el-input
                placeholder="请输入内容"
                clearable
                class="input"
                v-model="filterField.name"
              ></el-input>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item
                label="银行卡号"
                class="row-padding-bottom searchInput"
              >
                <el-select
                  v-model="filterField.bankCardNo"
                  filterable
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in bankCardList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item>
            <!-- <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchBrand"
              class="commonBtn"
            ></el-button> -->
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="getTableList(currentPage, pageSize)"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <!-- <el-button
              icon="icon iconfont icontianjia"
              @click="toAddPeople"
              class="commonBut saveBtn funComBut"
            > <span class="opetareText">添加人员</span></el-button> -->
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px">
          <el-button
            icon="icon iconfont icontianjia"
            @click="toAddPeople"
            class="commonBut saveBtn funComBut"
          >
            <span class="opetareText">添加人员</span>
          </el-button>
        </div>
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
          @row-click="clickRow"
          type="index"
          :row-class-name="tableRowClassName"
          @sort-change="sortChange"
          v-loading="loading"
        >
          <el-table-column
            type="index"
            width="80px"
            label="序号"
            align="center"
          ></el-table-column>
          <el-table-column prop="orgName" label="部门" width="230px">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.orgName"
                :columnName="'orgName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="idcard"
            label="身份证"
            align="center"
            width="175px"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="attDays"
            label="考勤天数"
            align="center"
            :formatter="formatTd"
            width="110"
          ></el-table-column>
          <el-table-column prop="tel" label="手机号" align="center" width="120">
            <template slot-scope="{ row, $index }">
              <div
                @click.stop="
                  {
                    {
                      changeNum($index, 'editBankInput')
                    }
                  }
                "
              >
                <el-input
                  v-if="editable[$index]"
                  v-model="row.tel"
                  size="mini"
                  class="editBankInput"
                ></el-input>
                <span v-else>{{ row.tel || '--' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="tel"
            label="银行卡号"
            align="center"
            width="185px"
          >
            <template slot-scope="{ row, $index }">
              <div
                @click.stop="
                  {
                    {
                      changeNum($index, 'editPersonBankCardInput')
                    }
                  }
                "
              >
                <el-input
                  v-if="editable[$index]"
                  v-model="row.bankCardNo"
                  size="mini"
                  class="editPersonBankCardInput"
                ></el-input>
                <span v-else>{{ row.bankCardNo || '--' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="shouldPay"
            label="应发工资"
            sortable="custom"
            align="center"
            width="120"
          >
            <template slot-scope="{ row, $index }">
              <div
                @click.stop="
                  {
                    {
                      changeNum($index, 'editSalaryInput')
                    }
                  }
                "
              >
                <el-input
                  v-if="editable[$index]"
                  v-model="row.shouldPay"
                  size="mini"
                  class="editSalaryInput"
                ></el-input>
                <span v-else>{{ row.shouldPay }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="230">
            <template slot-scope="{ row, $index }">
              <div
                @click.stop="
                  {
                    {
                      changeNum($index, 'editRemarkInput')
                    }
                  }
                "
              >
                <el-input
                  v-if="editable[$index]"
                  v-model="row.remark"
                  size="mini"
                  class="editRemarkInput"
                ></el-input>
                <span v-else>
                  <copyText
                    :tableIndex="$index"
                    :copyTextName="row.remark"
                    :columnName="'remark'"
                  ></copyText>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="130"
            align="left"
            fixed="right"
          >
            <template slot-scope="{ row, $index }">
              <el-link
                type="primary"
                @click.stop="handleSave(row, $index)"
                v-if="editable[$index]"
                >保存</el-link
              >
              <el-link
                type="primary"
                @click.stop="cancelSave(row, $index, 'true')"
                v-if="editable[$index]"
                >取消</el-link
              >
              <el-link
                type="primary"
                @click.stop="handleDelete(row, $index)"
                v-if="!editable[$index]"
                >删除</el-link
              >
              <!-- <i
              class="icon iconfont iconshanchu tabIcon delIcon"
              @click.stop="handleDelete(row , $index)"
              v-if="!editable[$index]"
            ></i> -->
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>

        <!-- <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          :isPackParams="isPackParams"
      ></Pagination>-->
        <el-col :span="24" class="toolbar" style="text-align: right">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            ref="pagination"
          ></el-pagination>
        </el-col>
        <el-col class="btnContainer">
          <el-button
            class="commonBut saveBtn"
            @click="isPay"
            :loading="isPyLoading"
            >上报</el-button
          >
          <el-button
            class="commonBut"
            @click="toSaveSalary"
            :loading="isSaveLoading"
            >保存</el-button
          >
        </el-col>
      </div>
    </div>

    <!--新增人员-->
    <el-dialog
      title="新增人员"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
      custom-class="brand-dialog-min-width"
      width="640px"
      :modal-append-to-body="false"
      class="oneColumnDialog"
    >
      <el-form
        :model="formData"
        label-width="135px"
        :rules="formRules"
        ref="formData"
        style="margin-top: 8px"
      >
        <el-form-item label="人员姓名：" prop="name" class="row-padding-bottom">
          <!-- <el-input v-model="formData.name" autocomplete="off"></el-input> -->
          <el-autocomplete
            class="el-input"
            id="autocompleteInput"
            v-model="formData.name"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入人员姓名"
            @select="handleSelect"
            :trigger-on-focus="false"
          >
            <template slot-scope="{ item }">
              <div class="name">
                {{ item.value }}
                <span class="fr">{{ item.idcard }}</span>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="身份证号：" class="row-padding-bottom">
          <el-input
            v-model="formData.idcard"
            autocomplete="off"
            disabled="disabled"
            placeholder="根据姓名带入身份证号"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="tel" class="row-padding-bottom">
          <el-input
            v-model="formData.tel"
            @blur="formData.tel = changeValue($event)"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="工资卡号："
          prop="bankCard"
          class="row-padding-bottom"
        >
          <el-input
            v-model="formData.bankCard"
            @blur="formData.bankCard = changeValue($event)"
            placeholder="请输入工资卡号"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="应发工资（元）："
          prop="shouldPay"
          class="row-padding-bottom"
        >
          <el-input
            v-model="formData.shouldPay"
            @blur="formData.shouldPay = changeValue($event)"
            placeholder="请输入应发工资"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：" class="row-padding-bottom">
          <el-input
            type="textarea"
            placeholder="如应发工资超过2万，可进行备注"
            v-model="formData.remark"
            @blur="formData.remark = changeValue($event)"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleClose" class="cancel">取消</el-button>
        <el-button
          type="primary"
          @click.native="addPeopleSubmit"
          class="save"
          :loading="isAddPropleLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import createSalaryStep from '@/components/publicCom/createSalaryStepJz'
import salaryTopTitle from '@/components/publicCom/salaryTopTitle'

export default {
  name: 'editSalary',
  components: {
    createSalaryStep,
    salaryTopTitle,
  },
  data() {
    return {
      salaryOperate: 'salaryOperate', //非建工资下载
      salaryExcel: 'salaryExcel', //非建工资模板
      lastItem: '编辑工资表',
      advanced: false,
      activeIndex: 1,
      // requestUrl:"api-su/salarydetail/base/vo",
      isPackParams: true,
      //下拉框数据
      orglist: [],
      //表格数据
      tableList: [],
      //分页
      currentPage: 1,
      total: 0,
      pageSize: 10,
      //搜索条件
      filterField: {
        organId: '',
        name: '',
        bankCardNo: '',
        // department: ""
      },
      orgId: '',
      editable: [], //是否可保存
      saveItem: '', //保存项
      formVisible: false, //添加人员弹窗
      formData: {
        name: '',
        idcard: '',
        shouldPay: '',
        tel: '',
        bankCard: '',
        remark: '',
        contractId: '',
        orgId: '',
      }, //添加人员数据
      formRules: {
        //添加人员表单验证
        name: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请输入人员姓名',
            trigger: 'change',
          },
        ],
        tel: [
          {
            // required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
        bankCard: [
          {
            required: true,
            pattern: /^\d{15,19}$/,
            message: '请输入15-19 位纯数字的银行卡号',
            trigger: 'blur',
          },
        ],
        shouldPay: [
          {
            required: true,
            pattern: /^\d{1,7}(\.\d{0,2})?$/,
            message: '请输入最多两位小数的正数',
            trigger: 'blur',
          },
        ],
      },
      isVerify: true,
      //人员姓名
      restaurants: [],
      state: '',
      timeout: null,
      // 页面传值
      salaryId: '',
      bankCardList: [
        {
          value: 'not null',
          label: '有银行卡号',
        },
        {
          value: 'null',
          label: '无银行卡号',
        },
      ],
      // 添加人员loading
      isAddPropleLoading: false,
      // 保存loading
      isSaveLoading: false,
      // 立即支付loading
      isPyLoading: false,
      // 记录编辑的那一行的原始数据
      firstObjP: {
        shouldPay: '',
        bankCardNo: '',
        tel: '',
        remark: '',
      },
      isShow: false,
      loading: true,
      // ie9定时器
      timer: null,
      isIE9: false,
      fromFullPath: '',
      type: '',
      year: '',
      month: '',
    }
  },
  created() {
    this.salaryId = this.$route.query.salaryId
    this.type = this.$route.query.type
    this.year = this.$route.query.year
    this.month = this.$route.query.month
    this.filterField.salaryId = this.salaryId
    // this.$nextTick(function() {
    //   this.$refs.pagination.getTableListData();
    // });
    this.getOrglist()
    this.getTableList(this.currentPage, this.pageSize)

    this.isIE()
  },
  mounted() {
    // this.restaurants = this.loadAll();
  },
  methods: {
    // getTableList(data) {
    //    // 验证条件置为原始值
    //   this.isVerify = true;
    //   this.tableList = data;
    // },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getTableList(currentPage, pageSize) {
      var data = {
        pageNo: currentPage,
        pageSize: pageSize,
        // "filterFieldName":filterFieldName
      }
      data.params = JSON.stringify(this.filterField)
      this.axios({
        method: 'post',
        url: 'api-su/salarydetail/base/vo',
        data: data,
      })
        .then(
          (response) => {
            this.tableList = response.data.result.results
            this.loading = false
            if (this.tableList.length < 1) {
              this.isShow = true
            }
            this.total = response.data.result.total
            this.editable = new Array(this.tableList.length)
            // this.saveItem = [];
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //每页显示多少条
    handleSizeChange(val) {
      this.isVerify = true

      for (var i = 0; i < this.editable.length; i++) {
        if (this.editable[i]) {
          this.$confirm('当前页面还有数据未保存, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              // 选中条数变为第一页
              this.currentPage = 1
              this.pageSize = val
              this.$refs.pagination.internalCurrentPage = this.currentPage
              this.getTableList(this.currentPage, val)
            })
            .catch(() => {})
          return
        } else {
        }
      }
      this.currentPage = 1
      this.pageSize = val
      this.$refs.pagination.internalCurrentPage = this.currentPage
      this.getTableList(this.currentPage, val)
    },
    //显示第几页
    handleCurrentChange(val) {
      this.isVerify = true
      for (var i = 0; i < this.editable.length; i++) {
        if (this.editable[i]) {
          this.$confirm('当前页面还有数据未保存, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              // 获取数据
              this.getTableList(val, this.pageSize)
            })
            .catch(() => {})
          return
        } else {
        }
      }
      // 获取数据
      this.getTableList(val, this.pageSize)
    },
    //获取部门
    getOrglist() {
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/orglist',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.orglist = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    handleChange(item) {
      var orgId = this.orgId[this.orgId.length - 1]

      this.filterField.organId = orgId
    },
    //表格过滤
    sortChange(column, prop, order) {
      // column：当前列
      // prop：当前列需要排序的数据
      // order：排序的规则（升序、降序和默认[默认就是没排序]）

      this.filterField.order = column.prop
      this.filterField.sort = column.order
      //  this.$refs.pagination.getTableListData();
      this.getTableList(this.currentPage, this.pageSize)
    },
    tableRowClassName({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = rowIndex
    },
    clickRow(row, column, event) {
      var index = row.index
      //验证点击的时候是否需要保存上一行数据
      if (this.editable[index]) {
      } else {
        if (this.saveItem) {
          if (
            this.firstObjP.bankCardNo == this.saveItem.bankCardNo &&
            this.firstObjP.remark == this.saveItem.remark &&
            this.firstObjP.shouldPay == this.saveItem.shouldPay &&
            this.firstObjP.tel == this.saveItem.tel
          ) {
            this.setEdit(index, '', 'row')
            return
          }
          this.verifyNum(this.saveItem, index, '', 'row')
          if (!this.isVerify) {
            return
          }
        } else {
          // //设置是否可以编辑
          this.setEdit(index, '', 'row')
          // this.editable = new Array(this.tableList.length);

          // this.editable[index] = true;
          // this.saveItem = this.tableList[index];
          // this.$set(this.editable, index, true);
        }
      }
    },
    changeNum(index, className) {
      //验证点击的时候是否需要保存上一行数据
      if (this.editable[index]) {
      } else {
        if (this.saveItem) {
          if (
            this.firstObjP.bankCardNo == this.saveItem.bankCardNo &&
            this.firstObjP.remark == this.saveItem.remark &&
            this.firstObjP.shouldPay == this.saveItem.shouldPay &&
            this.firstObjP.tel == this.saveItem.tel
          ) {
            this.setEdit(index, className, 'input')
            return
          }
          this.verifyNum(this.saveItem, index, className, 'input')
          if (!this.isVerify) {
            return
          } else {
          }
          // console.log("点击的不可编辑的行，需保存上一行数据");
        } else {
          this.setEdit(index, className, 'input')
        }
      }
    },
    setEdit(index, className, type) {
      //设置是否可以编辑
      this.editable = new Array(this.tableList.length)

      this.editable[index] = true

      this.saveItem = this.tableList[index]

      this.firstObjP = {
        shouldPay: this.saveItem.shouldPay,
        bankCardNo: this.saveItem.bankCardNo,
        tel: this.saveItem.tel,
        remark: this.saveItem.remark,
      }

      this.$set(this.editable, index, true)
      // 当应发工资为0，手动清除输入框中的数据
      if (this.saveItem.shouldPay == 0) {
        this.tableList[index].shouldPay = ''
      }

      if (type == 'input') {
        //focus
        this.$nextTick(function () {
          var editInputList = document.getElementsByClassName(className)
          editInputList[0].children[0].focus()
        })
      }
    },
    // 取消编辑
    cancelSave(row, index, isCancel) {
      // this.tableList[index] = this.demo;
      if (isCancel == 'true') {
        this.tableList[index].shouldPay = this.firstObjP.shouldPay
        this.tableList[index].bankCardNo = this.firstObjP.bankCardNo
        this.tableList[index].tel = this.firstObjP.tel
        this.tableList[index].remark = this.firstObjP.remark
      }

      this.editable = new Array(this.tableList.length)
      this.saveItem = ''
      // 验证条件置为原始值
      this.isVerify = true
    },
    // 搜索
    searchBrand() {
      // this.$refs.pagination.getTableListData();
      this.getTableList(this.currentPage, this.pageSize)
    },
    //验证编辑内容格式
    verifyNum(row, index, className, type) {
      var telReg = /^1[3456789]\d{9}$/
      var bankCardReg = /^\d{15,19}$/
      var moneyReg = /^\d{1,7}(\.\d{0,2})?$/
      // var remarkReg = /^([\u4E00-\u9FA5]{1,10} )||([A-Za-z0-9 ]{1,20})$/;
      this.isVerify = true
      var text = ''

      if (!telReg.test(row.tel) && row.tel) {
        text += '请输入正确的手机号;'
        this.isVerify = false
      }

      if (row.bankCardNo) {
        var bankCardNo = row.bankCardNo.replace(/\s/g, '')
      } else {
        var bankCardNo = ''
      }

      if (!bankCardReg.test(bankCardNo) && bankCardNo) {
        text += '请输入15-19 位纯数字的银行卡号;'
        this.isVerify = false
      }

      if (!moneyReg.test(row.shouldPay) && row.shouldPay) {
        text += '已超过金额最大值，请重新输入;'
        this.isVerify = false
      }

      if (row.remark && row.remark.length > 200) {
        text += '最多输入200字的备注;'
        this.isVerify = false
      }
      if (!this.isVerify) {
        this.$message({
          message: text,
          type: 'warning',
        })
      } else {
        this.savaSalary(row, index, className, type)
      }
    },
    // 保存
    savaSalary(row, index, className, type) {
      var data = {
        salaryId: this.salaryId, //工资表id
        detailId: row.salaryDetailId, //工资详情表id
        shouldPay: row.shouldPay, //应发工资
        bankCard: row.bankCardNo ? row.bankCardNo.replace(/\s/g, '') : '', //银行卡号
        tel: row.tel, //手机号
        remark: row.remark, //备注
      }
      var loading = this.$loading({
        lock: true,
        text: '保存中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })

      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/modifydetail',
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              loading.close()
              this.$message({
                message: '保存成功',
                type: 'success',
              })

              //需刷新
              this.$nextTick(function () {
                // this.$refs.pagination.getTableListData();
                this.getTableList(this.currentPage, this.pageSize)
                this.cancelSave(row, index)
              })

              // 需要判断
              if (type) {
                var that = this
                setTimeout(function () {
                  that.setEdit(index, className, type)
                }, 500)
              }
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
              // this.isVerify = false;
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
            loading.close()
          }
        )
        .catch((error) => {
          loading.close()
        })
    },
    //删除
    handleDelete(row, index) {
      const h = this.$createElement
      this.$msgbox({
        title: '删除人员',
        type: 'warning',
        message: h('p', null, [
          h('p', null, '是否确认工资表中删除 '),
          h('p', null, row.name + '-' + row.idcard + '?'),
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then((action) => {
          // this.$message({
          //   message: "删除成功",
          //   type: "success"
          // });
          this.delPeople(row, index)
        })
        .catch(() => {
          //     // this.$message.error("删除失败");
        })
    },
    delPeople(row, index) {
      var loading = this.$loading({
        lock: true,
        text: '处理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      var data = {
        salaryId: this.salaryId, //工资表id
        detailId: row.salaryDetailId, //工资详情id
      }
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/deletedetail',
        data: data,
      })
        .then(
          (response) => {
            loading.close()
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$nextTick(function () {
                // this.$refs.pagination.getTableListData();
                this.getTableList(this.currentPage, this.pageSize)
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
            }
          },
          (response) => {
            loading.close()
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {
          loading.close()
        })
    },
    //表格中的保存
    handleSave(row, index) {
      this.verifyNum(row, index)
    },
    //弹窗保存
    addPeopleSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isAddPropleLoading = true
          this.addPeople()
        } else {
          return false
        }
      })
    },
    toAddPeople() {
      this.formVisible = true
      this.formData = {
        name: '',
        idcard: '',
        shouldPay: '',
        tel: '',
        bankCard: '',
        remark: '',
        contractId: '',
        orgId: '',
      }
    },
    addPeople() {
      var data = {
        salaryId: this.salaryId,
      }

      data = Object.assign(data, this.formData)

      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/adddetail',
        data: data,
      })
        .then(
          (response) => {
            this.isAddPropleLoading = false
            if (!response.data.hasError) {
              this.$message({
                message: '添加成功',
                type: 'success',
              })
              this.formVisible = false
              //需要刷新列表
              this.$nextTick(function () {
                // this.$refs.pagination.getTableListData();
                this.getTableList(this.currentPage, this.pageSize)
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
            }
          },
          (response) => {
            this.isAddPropleLoading = false
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {
          this.isAddPropleLoading = false
        })
    },
    //关闭弹窗
    closeDialog() {
      this.$refs['formData'].resetFields()
    },
    //人员姓名
    querySearchAsync(queryString, cb) {
      let restaurants = this.restaurants
      // console.log(restaurants.length)
      // if (restaurants.length > 0) {
      //   // 如果参数都没变化，则使用缓存数据，避免请求沉积
      //   console.log("--不需要请求--")
      //   let results = queryString
      //     ? restaurants.filter(this.createFilter(queryString))
      //     : restaurants;
      //   cb(results);
      // } else {
      this.methodaa(queryString, cb, restaurants)
      // }
    },
    loadAll(data) {
      let serier = []
      if (data) {
        for (let i = 0, l = data.length; i < l; i++) {
          let item = data[i]

          serier.push({
            value: item.name,
            idcard: item.idcard,
            employeeId: item.employeeId,
            contractId: item.contractId,
            orgId: item.orgId,
            tel: item.tel,
            bankCardNo: item.bankCardNo,
          })
        }
      } else {
        // 如果没有请求到数据，则显示暂无数据！
        serier.push({ str: '暂无数据' })
      }
      return serier
    },

    createFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          // state.value
        )
      }
    },
    handleSelect(item) {
      this.formData.name = item.value
      this.formData.idcard = item.idcard
      this.formData.employeeId = item.employeeId
      this.formData.contractId = item.contractId
      this.formData.orgId = item.orgId
      this.formData.tel = item.tel
      this.formData.bankCard = item.bankCardNo
    },

    async getEmployeesForAddSalary() {
      var list = ''
      var data = {
        name: this.formData.name,
      }
      await this.axios({
        method: 'post',
        url: 'api-su/salary/expand/finddetail',
        data: data,
      })
        .then(
          (response) => {
            list = response.data
          },
          (response) => {}
        )
        .catch((error) => {})
      return list
    },
    methodaa(queryString, cb, restaurants) {
      var that = this
      that.getEmployeesForAddSalary().then(function (result) {
        if (result) {
          restaurants = that.loadAll(result)

          that.restaurants = restaurants

          let results = queryString
            ? restaurants.filter(that.createFilter(queryString))
            : restaurants
          cb(results)
          // do sth.
        } else {
          // do other sth.
        }
      })
    },
    handleClose() {
      this.formVisible = false
      this.$refs['formData'].resetFields()
    },
    // saveTable() {},
    // toPay() {},
    isPay() {
      this.isPyLoading = true
      this.axios({
        method: 'post',
        url: 'api-su/salary/base/validate',
        data: {
          salaryId: this.salaryId,
        },
      })
        .then(
          (response) => {
            this.isPyLoading = false
            if (!response.data.hasError) {
              this.canpPapOff(response.data.result)
            } else {
              if (response.data.result.isPayZero) {
                this.$message({
                  message: response.data.errorMsg,
                  type: 'warning',
                })
              } else if (response.data.result.isAccount) {
                this.noSalaryAccount()
              } else if (response.data.result.isBankCode) {
                this.noBankCard(response.data.errorMsg)
              }
            }
          },
          (response) => {
            this.isPyLoading = false
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {
          this.isPyLoading = false
        })
    },
    toPaySalary() {
      this.axios({
        method: 'post',
        url: 'api-su/salarydetail/base/confirmpay',
        data: {
          salaryId: this.salaryId,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              // this.$router.push({
              //   path: "/home/salary/paySalary",
              //   name: "paySalary",
              //   query: {
              //     salaryId: this.salaryId,
              //     type:this.type
              //   }
              // });
              this.$router.push({
                path: '/home/constructSalary/constructPaySalaryWay',
                name: 'constructPaySalaryWay',
                query: {
                  salaryId: this.salaryId,
                  year: this.year,
                  month: this.month,
                  type: this.type,
                  wherePage: 'fj', //非建
                },
              })
              this.$store.commit('CHANGE_SLIDER_NAME', {
                oldUrl: '/home/salary/qySalaryList',
                newUrl: this.$router.currentRoute.fullPath,
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {})
      // this.$router.push("/home/salary/paySalary");
    },
    toSaveSalary() {
      this.verifySaveItem(this.saveItem)
    },
    //验证编辑内容格式
    verifySaveItem(row) {
      var telReg = /^1[3456789]\d{9}$/
      var bankCardReg = /^\d{15,19}$/
      var moneyReg = /^\d{1,7}(\.\d{0,2})?$/
      // var remarkReg = /^([\u4E00-\u9FA5]{1,10} )||([A-Za-z0-9 ]{1,20})$/;
      var isVerify = true
      var text = ''

      if (!telReg.test(row.tel) && row.tel) {
        text += '请输入正确的手机号;'
        isVerify = false
      }

      if (row.bankCardNo) {
        var bankCardNo = row.bankCardNo.replace(/\s/g, '')
      } else {
        var bankCardNo = ''
      }

      if (!bankCardReg.test(bankCardNo) && bankCardNo) {
        text += '请输入15-19 位纯数字的银行卡号;'
        isVerify = false
      }

      if (!moneyReg.test(row.shouldPay) && row.shouldPay) {
        text += '已超过金额最大值，请重新输入;'
        isVerify = false
      }

      if (row.remark && row.remark.length > 200) {
        text += '最多输入200字的备注;'
        isVerify = false
      }
      //   console.log(row)
      if (row) {
        if (!isVerify) {
          this.$message({
            message: text,
            type: 'warning',
          })
        } else {
          this.saveSalary()
        }
      } else {
        this.saveSalary()
      }
    },
    //保存
    saveSalary() {
      var list = []
      for (var i = 0; i < this.tableList.length; i++) {
        var item = this.tableList[i]
        list.push({
          id: item.salaryDetailId,
          shouldPay: item.shouldPay,
          remark: item.remark,
          bankCard: item.bankCardNo,
          tel: item.tel,
        })
      }

      var data = {
        salaryDetails: JSON.stringify(list),
        salaryId: this.salaryId,
      }
      this.isSaveLoading = true
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/savesalarydetail',
        data: data,
      })
        .then(
          (response) => {
            this.isSaveLoading = false
            if (!response.data.hasError) {
              this.$message({
                message: '保存成功',
                type: 'success',
              })

              this.$nextTick(function () {
                // this.$refs.pagination.getTableListData();
                this.getTableList(this.currentPage, this.pageSize)
              })
              this.editable = new Array(this.tableList.length)
              this.saveItem = ''
            } else {
              this.$message({
                message: response.data.msg,
                type: 'warning',
              })
            }
          },
          (response) => {
            this.isSaveLoading = false
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    saveSalarySuccess() {
      this.$confirm(
        '已为您成功保存编辑的工资表, 您可以等以后有空再编辑或继续编辑?',
        '保存成功',
        {
          confirmButtonText: '继续编辑',
          cancelButtonText: '返回列表',
          type: 'success',
        }
      )
        .then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        })
        .catch(() => {
          this.goBack()
        })
    },
    noSalaryAccount() {
      this.$confirm(
        '您需先补充企业工资专户, 才能提交支付工资表',
        '工资专户未填写',
        {
          confirmButtonText: '前往完善',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          this.$router.push('/home/salary/salaryAccount')
          this.$store.commit('CHANGE_SLIDER_NAME', {
            oldUrl: '/home/salary/qySalaryList',
            newUrl: this.$router.currentRoute.fullPath,
          })
        })
        .catch(() => {})
    },
    noBankCard(number) {
      var html =
        '<div>您的工资表中有' +
        "<span style='color:red'>" +
        number +
        '人</span>未填写工资卡号，无法发工资，请填写后提交。</div>'
      this.$confirm(html, '温馨提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '返回编辑',
        cancelButtonText: '放弃提交',
      })
        .then((action) => {})
        .catch(() => {
          console.log('取消')
        })
    },
    canpPapOff(data) {
      var html =
        "<div style='font-size:16px'>请核对工资表的数据是否正确</div>" +
        '<div>应发工资总额：' +
        "<span style='color:red'>￥" +
        data.shouldPay +
        '</span></div>' +
        '<div>应发工资人数：' +
        "<span style='color:red'>" +
        data.shouldCount +
        '人</span>' +
        "&nbsp;&nbsp;<span style='color:#999'>(已排除" +
        data.excludeCount +
        '个应发工资等于0的人员)</span></div>'

      this.$confirm(html, '温馨提示', {
        dangerouslyUseHTMLString: true,
      })
        .then((action) => {
          this.toPaySalary()
        })
        .catch(() => {
          console.log('取消')
        })
    },
    clearTimer() {
      var that = this
      if (this.timer) {
        clearTimeout(this.timer)
      }
    },
    isIE() {
      if (
        navigator.appName == 'Microsoft Internet Explorer' &&
        parseInt(
          navigator.appVersion
            .split(';')[1]
            .replace(/[ ]/g, '')
            .replace('MSIE', '')
        ) == 9
      ) {
        //是IE
        this.isIE9 = true
      } else {
        this.isIE9 = false
      }
    },
    goBack() {
      // if(this.fromFullPath == "/home/salary/qySalaryList"){
      //   this.$router.push(this.fromFullPath);
      //   this.$store.commit("GOBACK_NAME", {oldUrl:"/home/salary/qySalaryList",newUrl:this.$router.currentRoute.fullPath});
      // }else if(this.fromFullPath == "/home/salary/paySalary"){

      // }else{
      //   this.$router.push(this.fromFullPath);
      //   this.$store.commit("CHANGE_SLIDER_NAME", {oldUrl:"/home/salary/qySalaryList",newUrl:this.$router.currentRoute.fullPath});
      // }
      // if(this.type == "create"){
      //   this.$router.push("/home/salary/createSalary");
      //   this.$store.commit("CHANGE_SLIDER_NAME", {oldUrl:"/home/salary/qySalaryList",newUrl:this.$router.currentRoute.fullPath});
      // }else if(this.type == "import"){
      //   this.$router.push("/home/salary/importSalary");
      //   this.$store.commit("CHANGE_SLIDER_NAME", {oldUrl:"/home/salary/qySalaryList",newUrl:this.$router.currentRoute.fullPath});
      // }else{
      this.$router.push('/home/salary/qySalaryList')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salary/qySalaryList',
        newUrl: this.$router.currentRoute.fullPath,
      })
      // }
    },
  },
  watch: {
    'formData.name': {
      handler(newVal, oldVal) {
        if (this.isIE9) {
          // ie9的操作
          if (oldVal) {
            if (newVal != oldVal) {
              this.clearTimer()
              this.timer = setTimeout(function () {
                $('#autocompleteInput').blur()
                $('#autocompleteInput').focus()
              }, 5000)
            }
          }
        }
      },
      deep: true,
      // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
      // immediate: true
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromFullPath = from.fullPath
    })
  },
}
</script>

<style scoped lang="less">
@import '../../../static/css/filterArea.less';
.mainCon {
  top: 197px;
  padding-top: 0;
  // padding: 24px;
}

/deep/.el-steps {
  padding: 30px 0;
}
.tableBox {
  padding: 24px;
}
.el-table td div span {
  display: inline-block;
  width: 100%;
}

.el-main {
  color: red;
}

// 弹窗样式
// .brand-dialog-min-width {
//   .el-form-item /deep/ label {
//     width: 130px !important;
//   }
//   .el-form-item /deep/ .el-form-item__content {
//     margin-left: 130px !important;
//   }
//   .el-form-item /deep/ .el-textarea__inner {
//     height: 130px;
//   }
// }

.btnContainer {
  text-align: center;
  padding: 30px 0;
}

@media screen and (max-width: 1280px) {
  .input /deep/ .el-input__inner {
    width: 160px;
  }
  .searchInput /deep/ .el-input__inner {
    width: 190px;
  }
}

@media all and (min-width: 1360px) and (max-width: 1470px) {
  .input /deep/ .el-input__inner {
    width: 160px;
  }
  .searchInput /deep/ .el-form-item__label {
    width: 68px;
  }
}

.saveBtn /deep/ .iconfont {
  // padding: 0 5px;
  font-size: 14px;
}
@import '../../../static/css/filterArea.less';
</style>
